<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin extends Controller_Site 
{
	
	public $auth_required = 'admin';
	
	public function before() {
		parent::before();
		
		$this->template->title = "Panel de Administración";
	}
	
	
	public function action_users() {
		$this->site->content = new View('admin/users');
		$this->site->content->users = Model::factory('user')->find_all();
		
		$this->template->styles = array(
			URL::base() . 'media/site/css/default.css' => "screen",
			URL::base() . 'media/admin/css/default.css' => "screen",
		);
	}
	
	public function action_blockUser() {
		$user_id = $_GET["user"];
		$user = ORM::factory('user', $user_id);
		if($user->loaded()) {
			$user->remove('roles', ORM::factory('role', array('name' => 'login')));
		}
		$this->request->redirect(URL::site("admin/users"));
	}
	
	public function action_recoverUser() {
		$user_id = $_GET["user"];
		$user = ORM::factory('user', $user_id);
		if($user->loaded()) {
			$user->add('roles', ORM::factory('role', array('name' => 'login')));
		}
		$this->request->redirect(URL::site("admin/users"));
	}
	
	public function action_books() {
		$books = ORM::factory('book')->find_all();
		$this->site->content = new View('admin/books');
		$this->site->content->books = $books;
	}
	
	public function action_newBook() {
		$this->site->content = new View('admin/newBook');
		
		if($_POST){
			$post = Validation::factory($_POST);
			
			$post->rule('title', 'not_empty')
				->rule('isbn', 'not_empty');
				
			if($post->check()){
				$book = ORM::factory("book");
				$book->isbn = $post['isbn'];
				$book->title = $post['title'];
				if(isset($_POST['brain_score'])) {
					$book->brain_score = $_POST['brain_score'];
				}
				if(isset($_POST['description'])) {
					$book->description = $_POST['description'];
				}	
				$book->save();
				$this->request->redirect(URL::site("admin/books"));
			}else{
				$errors = array("Hubo errores en los datos ingresados.");
				$this->site->content->bind('errors', $errors);
				$this->site->content->bind('post', $post);
			}
		}
		
	}
	
}
	